package com.mcr.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**全局异常处理
 *1.@ControllerAdvice，是Spring3.2提供的新注解,它是一个Controller增强器,
 *  可对controller中被@RequestMapping注解的方法加一些逻辑处理。最常用的就是异常处理
 *2.ControllerAdvice本质上是一个Component；
 *3.ControllerAdvice 提供了多种指定Advice规则的定义方式，默认什么都不写，则是Advice所有Controller；
 *4.@ControllerAdvice 配合 @ExceptionHandler 实现全局异常处理；
 */

@ControllerAdvice(annotations = {RestController.class, Controller.class})
//拦截加RestController, Controller
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException es){
        String msg="未知错误，添加失败";
        if(es.getMessage().contains("Duplicate entry")){
            //判断异常信息是否包含”Duplicate entry“
            String[] s = es.getMessage().split(" ");
            msg="名称："+s[2]+"重复，添加失败";
        }
        return R.error(msg);
    }
    @ExceptionHandler(CustomException.class)
    public R<String> CustomExceptionHandler(CustomException ce){
        String msg=ce.getMessage();
        log.error(msg);
        return R.error(msg);
    }
}
